#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <filesystem>
#include <sstream>
#include <fstream>
#include <memory>
#include <ctime>
#include <unistd.h>
#include "Mutex.hpp"

namespace LogModule
{
    const static std::string gsep = "/r/n";
    using namespace MutexModule;
    class LogStrategy
    {
        public:
        virtual void Strategy(const std::string& message) = 0;
    };

    class ConsoleStrategy : public LogStrategy
    {
        public:
        ConsoleStrategy()
        {

        }
        ~ConsoleStrategy()
        {

        }

        void Strategy(const std::string& message) override
        {
            LockGuard lockguard(_mutex);
            std::cout <<message <<std::endl;
        }
        private:
        Mutex _mutex;
    };

    class FileStrategy : public LogStrategy
    {
        public:
        FileStrategy(){}
        FileStrategy(const std::string& path , const std::string& file)
            :_path(path)
            ,_file(file)
            {
                LockGuard lockguard(_mutex);
                if(std::filesystem::exists(_path))
                {
                    return ;
                }
                try
                {
                    std::filesystem::create_directories(_path);
                }
                catch(const std::filesystem::filesystem_error& err)
                {
                    std::cerr << err.what() << '\n';
                }
            }

        void Strategy(const std::string& message) override
        {
            LockGuard lockguard(_mutex);
            _filename = _path + (_path.back() == '/' ? "" : "/") + _file;
            std::ofstream out(_filename , std::ios::app);
            if(!out.is_open())
            {
                return ;
            }
            out << message <<gsep;
            out.close();
        }
        private:
        Mutex _mutex;
        std::string _filename;
        std::string _path;
        std::string _file;
    };

    enum class LogLevel
    {
        INFO,
        DEBUG,
        FATAL,
        ERROR,
        WARNNING
    };

    std::string LevelToStr(LogLevel level)
    {
        switch(level)
        {
            case LogLevel::DEBUG:
                return "DEBUG";
            case LogLevel::ERROR:
                return "ERROR";
            case LogLevel::FATAL:
                return "FATAL";
            case LogLevel::INFO:
                return "INFO";
            case LogLevel::WARNNING:
                return "WARNNING";
            default:
                return "UNKONWED";
        }
    }

    std::string GetTimeStamp()
    {
        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr , &curr_tm);
        char time_buffer [128];
        snprintf(time_buffer , sizeof(time_buffer) , "%4d-%02d-%02d %02d:%02d:%02d",
                curr_tm.tm_year + 1900, 
                curr_tm.tm_mon + 1,
                curr_tm.tm_mday,
                curr_tm.tm_hour,
                curr_tm.tm_min,
                curr_tm.tm_sec);

        return time_buffer;
    }


    class Logger
    {
        public:
        Logger()
        {
            EnableConsoleStategy();
        }

        void EnableConsoleStategy()
        {
            _fflush_strategy = std::make_unique<ConsoleStrategy>();
        }

        void EnableFileStategy()
        {
            _fflush_strategy = std::make_unique<FileStrategy>();
        }

        class LogMessage
        {
            public:
            LogMessage(LogLevel level , std::string scr_name , int line , Logger& logger)
                :_curr_time(GetTimeStamp())
                ,_scr_name(scr_name)
                ,_line(line)
                ,_logger(logger)
                ,_pid(getpid())
                ,_level(level)
            {

                std::stringstream ss;
                ss << "[" << _curr_time << "]"
                   << "[" << LevelToStr(_level) << "]"
                   << "[" << _pid << "]"
                   << "[" << _scr_name << "]"
                   << "[" << _line << "]";

                _loginfo = ss.str();
            }
            
            template<typename T>
            LogMessage& operator<<(const T & data)
            {
                std::stringstream ss;
                ss << data ;
                _loginfo = _loginfo + ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if(_logger._fflush_strategy != nullptr)
                {
                    _logger._fflush_strategy->Strategy(_loginfo);
                }
            }
            private:
            std::string _curr_time;
            LogLevel _level;
            std::string _scr_name;
            int _line;
            Logger& _logger;
            std::string _loginfo;
            pid_t _pid;
        };
        
        LogMessage operator()(LogLevel level , std::string scr_name , int line )
        {
            return LogMessage(level ,scr_name , line, *this );
        }
        ~Logger()
        {
            
        }
        private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };


    Logger logger;

    #define LOG(level) logger(level , __FILE__ , __LINE__)
    #define Enable_Console_Strategy() logger.EnableConsoleStategy()
    #define Enable_File_Strategy() logger.EnableFileStategy()
}
